import db from './createDb'
import Mock from 'mockjs'
import { parseUrl, pick } from '../assets/utils/toolFunction'

// 添加产品
Mock.mock('product/add', 'post', ({ body }) => {
  const { pid, title, summary = '', picture, price, total, content = '', state = 1 } = JSON.parse(body)

  db.add('zy_products', { pid, title, summary, picture, price, total, content, state })
  return {
    err: 0,
    desc: '添加成功'
  }
})

// 读取产品列表信息
Mock.mock(/product\/list(\?.+)?/, 'get', ({ url }) => {
  let { state, pid, price, keyword = '', page, pageSize } = parseUrl(url)
  // 转为数字
  state = +state
  price = price ? price.split('-') : false
  page = +page
  pageSize = +pageSize
  // 处理中文乱码问题
  keyword = decodeURIComponent(keyword)
  console.log(state, price, page = 1, pageSize, keyword)

  const searchResult = db.select('zy_products', item => {
    // 搜索条件
    return (item.state === state || !state) &&
    (item.pid === +pid || !pid) &&
    (item.price > price[0] && item.price <= price[1] || !price) &&
    (item.title.includes(keyword) || !keyword)
  })

  const total = searchResult.length
  const totalPage = Math.ceil(total / pageSize)
  if (page > totalPage) page = totalPage
  const start = (page - 1) * pageSize
  const end = start + pageSize

  console.log(start, end)
  const pageResult = searchResult.slice(start, end)

  return { err: 0, result: pageResult, page, total, totalPage, pageSize, desc: '查询成功' }
})

// 修改用户
Mock.mock('product/updata', 'post', ({ body }) => {
  const { id, pid, title, summary = '', picture, price, total, content = '', state = 1 } = JSON.parse(body)

  db.put('zy_products', id, { pid, title, summary, picture, price, total, content, state })
  return {
    err: 0,
    desc: '修改成功'
  }
})

// 修改state状态
Mock.mock('product/state', 'post', ({ body }) => {
  const { id, state } = JSON.parse(body)
  db.put('zy_products', id, { state })
  return {
    err: 0,
    desc: '状态修改成功'
  }
})

// 删除用户
Mock.mock('product/delete', 'post', ({ body }) => {
  const { ids } = JSON.parse(body)
  db.delete('zy_products', ids)
  return {
    err: 0,
    desc: '删除成功'
  }
})
